package com.shawn.example.mvvmdemo.home.ui.home

import android.text.Html
import android.view.View
import android.widget.ImageView
import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jetpack.mvvm.lib.common.utils.ImageLoader
import com.shawn.example.mvvmdemo.home.R
import com.shawn.example.mvvmdemo.home.databinding.ItemHomeListBinding
import com.shawn.example.mvvmdemo.home.model.ArticleDetail


class HomeAdapter(data: MutableList<ArticleDetail>) : BaseQuickAdapter<ArticleDetail, BaseViewHolder>(R.layout.item_home_list, data) {

    override fun convert(holder: BaseViewHolder, item: ArticleDetail) {
        val authorStr = item.author.ifEmpty { item.shareUser }
        val bind : ItemHomeListBinding = ItemHomeListBinding.bind(holder.itemView)
        holder.setText(R.id.tv_article_title, Html.fromHtml(item.title))
            .setText(R.id.tv_article_author, authorStr)
            .setText(R.id.tv_article_date, item.niceDate)
            .setImageResource(
                R.id.iv_like,
                if (item.collect) R.drawable.ic_like else R.drawable.ic_like_not
            )
        val chapterName = when {
            item.superChapterName.isNotEmpty() and item.chapterName.isNotEmpty() ->
                "${item.superChapterName} / ${item.chapterName}"
            item.superChapterName.isNotEmpty() -> item.superChapterName
            item.chapterName.isNotEmpty() -> item.chapterName
            else -> ""
        }
        holder.setText(R.id.tv_article_chapterName, chapterName)
        if (item.envelopePic.isNotEmpty()) {
            holder.getView<ImageView>(R.id.iv_article_thumbnail)
                .visibility = View.VISIBLE
            context.let {
                ImageLoader.load(it, item.envelopePic, holder.getView(R.id.iv_article_thumbnail))
            }
        } else {
            holder.getView<ImageView>(R.id.iv_article_thumbnail)
                .visibility = View.GONE
        }
        bind.tvArticleFresh.isVisible = item.fresh
        bind.tvArticleTop.isVisible = item.top == "1"
        if (item.tags.isNotEmpty()) {
            bind.tvArticleTag.visibility = View.VISIBLE
            bind.tvArticleTag.text = item.tags[0].name
        } else {
            bind.tvArticleTag.visibility = View.GONE
        }
    }

}
